package com.kfm.base.io.o;

import java.io.*;

public class Demo07 {

    public static void main(String[] args) {
        // 通过序列化和反序列化实现深克隆
        Student friend = new Student("张兴成", 60.1, "男");

        Student stu = new Student("秦爽", 59.9, "男");

        stu.setFriend(friend);

        System.out.println(stu);

        try {
            // 序列化
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            oos.writeObject(stu);

            byte[] byteArray = outputStream.toByteArray();

            // 反序列化
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(byteArray));

            Object o = ois.readObject();

            if (o instanceof Student copy){
                System.out.println(copy == stu);
                System.out.println(copy.getFriend() == stu.getFriend());
                System.out.println(copy);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
